<script lang="ts" setup name="Depts">
import { onMounted, ref, reactive } from 'vue';
import { Plus, Upload, Download } from '@element-plus/icons-vue'
import { searchDeptApi, createDeptApi, updateDeptApi, deleteDeptByIdApi, getDeptTreeApi } from '@/api/system/depts/index'
import { FormInstance } from 'element-plus'
import { resetForm } from '@/utils/common'
import { Dept } from '@/api/system/depts/type';
import { Menu } from '@/api/system/menus/type';

const multipleSelection = ref<(string | number)[]>([])
const handleSelectionChange = (menus: Menu[]) => {
    multipleSelection.value = menus.map(menu => menu.id)
}
// 部门表格数据
const tableData = ref([])
const treeSelectData = ref<any[]>([])

// 查询表单
// 查询表单关联
const queryFormRef = ref<FormInstance>()
// 查询表单数据
const queryForm = reactive({
    name: '',
})

const search = async () => {
    const res = await searchDeptApi(queryForm.name)
    if (res.data.code == 200) {
        tableData.value = res.data.data
    }
}

const resetQuery = () => {
    queryForm.name = ''
    getDeptTree()
}

// 获取部门树数据
const getDeptTree = async () => {
    const res = await getDeptTreeApi()
    if (res.data.code == 200) {
        tableData.value = res.data.data
    }
}

const getTreeSelectData = async () => {
    const res = await getDeptTreeApi()
    if (res.data.code == 200) {
        treeSelectData.value = [{
            id: "0",
            name: '顶级部门',
            children: res.data.data
        }]
    }
}

// 抽屉
// 抽屉控制
const drawer = reactive({
    visible: false,
    mode: ''
})
// 部门表单关联
const drawerFormRef = ref<FormInstance>()
// 部门
const dept = ref<Dept>({
    id: '',
    children: [],
    name: '',
    type: '',
    sort: 0,
    parentId: ''
})
// 添加按钮点击事件
const addClick = (rowData: any) => {
    drawer.visible = true
    drawer.mode = 'add'
    dept.value.parentId = rowData.id
}
// 编辑按钮点击事件
const editClick = (rowData: any) => {
    drawer.visible = true
    drawer.mode = 'update'
    nextTick(() => {
        dept.value = { ...rowData }
    })
}
// 添加/编辑页面关闭之前处理
const handleClose = (done: () => void) => {
    resetForm(drawerFormRef.value)
    done()
}
// 添加/编辑事件提交
const submit = async () => {
    try {
        const { children, ...data } = dept.value
        if (drawer.mode == 'add') {
            await createDeptApi(data)
        } else if (drawer.mode == 'update') {
            await updateDeptApi(data)
        }
        drawer.visible = false
        getDeptTree()
        ElMessage.success('提交成功')
    } catch (err) {
        ElMessage.error('提交失败')
    }

}
// 删除部门及其下级部门
const deleteClick = async (row: Dept) => {
    try {
        const { data } = await deleteDeptByIdApi(row.id)
        if (data.code == '200') {
            getDeptTree()
            ElMessage.success('删除成功')
        }
    } catch (err) {
        ElMessage.error('删除失败')
    }
}

onMounted(() => {
    getDeptTree()
})
</script>

<template>
    <div h-full flex flex-col gap-row-4 box-border w-full>
        <div style="box-shadow: var(--el-box-shadow);" w-full box-border>
            <el-form :inline="true" :model="queryForm" style="margin: 1rem 1rem 0 1rem" ref="queryFormRef">
                <el-form-item label="机构名称" prop="name">
                    <el-input v-model="queryForm.name" placeholder="请输入机构名称" clearable />
                </el-form-item>
                <el-form-item>
                    <el-button @click="search()">查询</el-button>
                    <el-button @click="resetQuery()">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div flex-1 overflow-hidden box-border position-relative pt-2 style="box-shadow: var(--el-box-shadow);">
            <div flex flex-col overflow-hidden box-border position-absolute w-full h-full>
                <div flex flex-justify-end p-4>
                    <ElButton :icon="Plus" circle @click="addClick"></ElButton>
                    <ElButton :icon="Upload" circle></ElButton>
                    <ElButton :icon="Download" circle></ElButton>
                </div>
                <div flex-1 overflow-hidden box-border>
                    <ElTable :data="tableData" w-full box-border :border="true" height="100%" row-key="id" 
                        @selection-change="handleSelectionChange">
                        <el-table-column prop="name" label="机构名称"  />
                        <el-table-column prop="status" label="状态"   />
                        <el-table-column prop="sort" label="排序"  />
                        <el-table-column prop="createTime" label="创建时间"  />
                        <el-table-column fixed="right" label="操作">
                            <template #default="scope">
                                <div flex flex-justify-around flex-items-center>
                                    <el-tooltip content="新增子项">
                                        <ElIcon @click="addClick(scope.row)">
                                            <i i-ep-circle-plus />
                                        </ElIcon>
                                    </el-tooltip>
                                    <el-tooltip content="编辑">
                                        <ElIcon @click="editClick(scope.row)">
                                            <i i-ep-edit />
                                        </ElIcon>
                                    </el-tooltip>
                                    <el-tooltip content="删除">
                                        <div flex>
                                            <el-popconfirm title="你确认该部门及其下级部门吗?" confirm-button-text="确认"
                                                cancel-button-text="取消" @confirm="deleteClick(scope.row)">
                                                <template #reference>
                                                    <ElIcon>
                                                        <i i-ep-delete />
                                                    </ElIcon>
                                                </template>
                                            </el-popconfirm>
                                        </div>
                                    </el-tooltip>
                                </div>
                            </template>
                        </el-table-column>
                    </ElTable>
                </div>
            </div>
        </div>
        <!-- 新增/修改抽屉组件 -->
        <el-drawer v-model="drawer.visible"
            :title="drawer.mode == 'add' ? '创建部门' : (drawer.mode == 'update' ? '编辑部门' : '')" direction="rtl"
            :before-close="handleClose">
            <el-form :model="dept" label-width="auto" ref="drawerFormRef">
                <el-form-item label="机构名" prop="name">
                    <el-input v-model="dept.name" />
                </el-form-item>
                <el-form-item label="上级机构" prop="parentId">
                    <el-tree-select v-model="dept.parentId" check-strictly :data="treeSelectData" @focus="getTreeSelectData()" placeholder="请选择上级部门" :props="{ value: 'id', label: 'name', children: 'children' }" />
                </el-form-item>
                <el-form-item label="状态" prop="status">
                </el-form-item>
                <el-form-item label="排序" prop="sort">
                    <el-input-number v-model="dept.sort" class="mx-4" :min="0" controls-position="right" />
                </el-form-item>
            </el-form>
            <template #footer>
                <ElDivider />
                <ElButton size="large" @click="submit">提交</ElButton>
            </template>
        </el-drawer>
    </div>
</template>

<style scoped lang="scss"></style>